package com.sunny.lock;

import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class Consumer implements Runnable{

    private String name;
    private Queue<Integer> queue;
    private int max;
    private Lock lockProducer;
    private Lock lockConsumer;
    private Condition full;
    private Condition empty;

    public Consumer(Lock lockProducer, Lock lockConsumer, Condition full, Condition empty, int max, Queue<Integer> queue, String name) {
        this.lockProducer = lockProducer;
        this.lockConsumer = lockConsumer;
        this.full = full;
        this.empty = empty;
        this.max = max;
        this.queue = queue;
        this.name = name;
    }

    @Override
    public void run() {

        while (true){
            lockConsumer.lock();
            try {
                if (queue.size() <= 0){
                    empty.await();
                }
                queue.poll();

                System.out.println("消费者"+name+"消费了一个产品。当前产品队列长度为："+queue.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lockConsumer.unlock();
            }

            if(queue.size() < max){
                lockProducer.lock();
                try {
                    full.signalAll();
                }finally {
                    lockProducer.unlock();
                }
            }

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}
